import { ConnectAction } from '../action'
import type { Connect } from '../index'
import type { VerifyInfo } from '../types'

/**
 * 发起验证
 */
export class InitiateVerifyAction extends ConnectAction {
  constructor(connect: Connect) {
    super('initiateVerify', connect)

    this.addAsyncAction('sendVerifyInfo', this.sendVerifyInfo_handler, true)
    this.addAsyncAction('receiveVerifyResult', this.receiveVerifyResult_handler)

    this.actions.addBranchChain('sendVerifyInfo', 'receiveVerifyResult')
  }

  async sendVerifyInfo_handler() {
    const info = this.connect.store.get<VerifyInfo>('verifyInfo')
    if (!info) throw new Error('verify info not found')
    await this.connect.sendJson(info)
  }

  async receiveVerifyResult_handler() {
    const p = await this.connect.packetOnceAsync()

    if (!p.isOk()) {
      const msg = p.readErrorContent() || 'verify fail'
      throw new Error(msg)
    }
  }
}
